package com.zhuoyue.web.controller.system;

import com.zhuoyue.common.annotation.Log;
import com.zhuoyue.common.constant.UserConstants;
import com.zhuoyue.common.core.controller.BaseController;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.domain.entity.SysUser;
import com.zhuoyue.common.core.domain.entity.TblProductCategory;
import com.zhuoyue.common.enums.BusinessType;
import com.zhuoyue.common.utils.DealLogUtils;
import com.zhuoyue.common.utils.SecurityUtils;
import com.zhuoyue.common.utils.ServletUtils;
import com.zhuoyue.common.utils.StringUtils;
import com.zhuoyue.common.utils.poi.ExcelUtil;
import com.zhuoyue.system.service.TblDeviceZYCategoryService;
import com.zhuoyue.web.utils.OrgCodeUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 设备分类信息
 *
 * @author hewenze
 */
@RestController
@Api(value = "设备分类管理接口", tags = "设备分类管理接口")
@RequestMapping("/system/deviceCategory")
public class TblDeviceZYCategoryController extends BaseController {
    private final TblDeviceZYCategoryService tblDeviceZYCategoryService;

    @Autowired
    private OrgCodeUtils orgCodeUtils;

    @Autowired
    private DealLogUtils dealLogUtils;

    public TblDeviceZYCategoryController(TblDeviceZYCategoryService tblDeviceZYCategoryService) {
        this.tblDeviceZYCategoryService = tblDeviceZYCategoryService;
    }

    /**
     * 获取设备分类列表
     */
    @GetMapping("/list")
    public AjaxResult list(TblProductCategory productCategory) {
        List<TblProductCategory> list = tblDeviceZYCategoryService.selectProductCategoryList(productCategory);
        return AjaxResult.success(list);
    }

    /**
     * 获取设备分类列表
     */
    @GetMapping("/export")
    public AjaxResult export(TblProductCategory productCategory) {
        List<TblProductCategory> list = tblDeviceZYCategoryService.selectProductCategoryList(productCategory);
        ExcelUtil<TblProductCategory> util = new ExcelUtil<>(TblProductCategory.class);
        return util.exportExcel(list, "产品类型");
    }

    /**
     * 获取设备分类列表
     */
    @GetMapping("/listForApp")
    public AjaxResult listForApp(TblProductCategory productCategory) {
        List<TblProductCategory> list = tblDeviceZYCategoryService.selectProductCategoryListForApp(productCategory);
        return AjaxResult.success(list);
    }

    /**
     * 查询设备分类列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<TblProductCategory> depts = tblDeviceZYCategoryService.selectProductCategoryList(new TblProductCategory());
        Iterator<TblProductCategory> it = depts.iterator();
        while (it.hasNext()) {
            TblProductCategory d = (TblProductCategory) it.next();
            if (d.getCategoryId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据设备分类编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(tblDeviceZYCategoryService.selectDeptById(deptId));
    }

    /**
     * 获取设备分类下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(TblProductCategory dept) {
        List<TblProductCategory> depts = tblDeviceZYCategoryService.selectProductCategoryList(dept);
        return AjaxResult.success(tblDeviceZYCategoryService.buildDeptTreeSelect(depts));
    }


    /**
     * 新增设备分类
     */
    @Log(title = "产品类型添加", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TblProductCategory productCategory) {
        String classAndMethodName = this.getClass().getName() + "." + "add()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

        if (UserConstants.NOT_UNIQUE.equals(tblDeviceZYCategoryService.checkDeptNameUnique(productCategory))) {
            return AjaxResult.error("新增分类'" + productCategory.getCategoryNum() + "'失败，分类名称已存在");
        }
        productCategory.setCreateBy(SecurityUtils.getUsername());
        tblDeviceZYCategoryService.insertDept(productCategory);

        // 添加后的数据
        TblProductCategory targetData = tblDeviceZYCategoryService.selectDeptById(productCategory.getCategoryId());
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, null, targetData);
        return AjaxResult.success();
    }

    /**
     * 修改设备分类信息
     */
    @Log(title = "产品类型修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TblProductCategory dept) {
        // 修改前的数据
        TblProductCategory sourceData = tblDeviceZYCategoryService.selectDeptById(dept.getCategoryId());
        String classAndMethodName = this.getClass().getName() + "." + "edit()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

        if (UserConstants.NOT_UNIQUE.equals(tblDeviceZYCategoryService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改分类'" + dept.getCategoryNum() + "'失败，分类名称已存在");
        } else if (dept.getParentId().equals(dept.getCategoryId())) {
            return AjaxResult.error("修改分类'" + dept.getCategoryNum() + "'失败，上级分类不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && tblDeviceZYCategoryService.selectNormalChildrenDeptById(dept.getCategoryId()) > 0) {
            return AjaxResult.error("该分类包含未停用的子分类！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        tblDeviceZYCategoryService.updateDept(dept);

        // 修改后的数据
        TblProductCategory targetData = tblDeviceZYCategoryService.selectDeptById(dept.getCategoryId());
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, sourceData, targetData);
        return AjaxResult.success();
    }

    /**
     * 删除设备分类
     */
    @Log(title = "产品类型删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceCategoryId}")
    public AjaxResult remove(@PathVariable Long deviceCategoryId) {
        // 删除前的数据
        TblProductCategory sourceData = tblDeviceZYCategoryService.selectDeptById(deviceCategoryId);
        String classAndMethodName = this.getClass().getName() + "." + "remove()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

        if (tblDeviceZYCategoryService.hasChildByDeptId(deviceCategoryId)) {
            return AjaxResult.error("存在下级分类,不允许删除");
        }

        tblDeviceZYCategoryService.deleteDeptById(deviceCategoryId);

        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, sourceData, null);
        return AjaxResult.success();
    }
}
